package wangjg.sso;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ValidateParameters {

	private String salt;
	private String tokenKey="~v";
	private String timeKey="~t";
	private long timeout = 1000*60;
	
	public boolean validate(String params){
		String spliter=tokenKey+"=";
		int i=params.indexOf(spliter);
		if(i==-1){
			return false;
		}
		String token=params.substring(i+spliter.length());
		String params1=params.substring(0,i-1);
		long t= Long.parseLong(this.getParam(params1, timeKey));
		if(System.currentTimeMillis()-t>timeout ){
			return false;
		}
		String encrypted=getValidation(params1);
		System.out.println(encrypted+"="+encrypted.length());
		if(!encrypted.equals(token)){
			return false;
		}
		return true;
	}
	
	private String getParam(String params,String key){
		String regex=key+"="+"([^&]+)";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(params);
        if(m.find())
        	return m.group(1);
        return null;
	}
	
	public String encrypt(String params){
		long t=System.currentTimeMillis();
		String str=params+"&"+timeKey+"="+t;
		str = str+"&"+tokenKey+"="+getValidation(str);
		return str;
	}
	
	private String getValidation(String str){
		return _sha(str+salt);
	}
	
	private String _md5(String str) {
		String encodeStr = "";
		byte[] digesta = null;
		try {
			MessageDigest alg = MessageDigest.getInstance("MD5");
			alg.update(str.getBytes());
			digesta = alg.digest();
			encodeStr = byte2hex(digesta);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return encodeStr;
	}
	
	private String _sha(String str){
		if(str==null)
			return null;
        try {
    		byte[] bytes=str.getBytes();
        	MessageDigest digest = MessageDigest.getInstance("SHA-1");
        	digest.update(bytes);  
            return byte2hex(digest.digest());
        }  
        catch (NoSuchAlgorithmException e) {  
            e.printStackTrace();  
            return null;  
        }
	}
	
	private static String byte2hex(byte[] piByte) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < piByte.length; i++) {
			int v = piByte[i] & 0xFF;
			if (v < 16)
				sb.append('0');
			sb.append(Integer.toString(v, 16).toLowerCase());
		}
		return sb.toString();
	}
	
	public static void main(String args[]) throws Exception{
		ValidateParameters vp=new ValidateParameters();
		String params="username=wjg";
		String str=vp.encrypt(params);
		System.out.println(str);
		System.out.println(vp.validate(str));
	}
}
